import CryptoJS from 'crypto-js';

class Crypto {
  encrypt(str: string, key: string, iv: string) {
    const keyHex = CryptoJS.enc.Utf8.parse(key); //
    const ivHex = CryptoJS.enc.Utf8.parse(iv);
    const messageHex = CryptoJS.enc.Utf8.parse(str);
    const encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, {
      iv: ivHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return this.replaceSpecialChar(encrypted.toString());
  }

  decrypt(str: string, key: string, iv: string) {
    // 如果加密后没有转成base64,那么先要转成base64再传入
    str = this.replaceSpecialChar(str);
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const ivHex = CryptoJS.enc.Utf8.parse(iv);
    const decrypt = CryptoJS.AES.decrypt(str, keyHex, {
      iv: ivHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
  }

  replaceSpecialChar(str: string) {
    if (!str) {
      return '';
    }
    if (str.indexOf('=') > -1) {
      str = str.replaceAll('=', '_I2F_I2F');
    } else if (str.indexOf('_I2F_I2F') > -1) {
      str = str.replaceAll('_I2F_I2F', '=');
    }
    return str;
  }
}

export default new Crypto();
